const express = require('express')
const pool = require('../db')
const utility = require('utility')
const router = express.Router()

// 获取用户基本信息
router.get('/userinfo', (req, res) => {
  // console.log(req.user.username)
  pool.query(
    'select * from user where username = ?',
    req.user.username,
    (err, results) => {
      // console.log(results)
      if (results.length > 0) {
        const { id, username, nickname, email, user_pic } = results[0]
        res.send({
          status: 0,
          message: '获取用户基本信息成功',
          data: {
            id,
            username,
            nickname,
            email,
            user_pic,
          },
        })
      } else {
        res.send({
          status: 1,
          message: '获取用户信息失败',
        })
      }
    }
  )
})

// 修改用户基本信息
router.post('/userinfo', (req, res) => {
  const { id, nickname, email } = req.body
  pool.query(
    'update user set nickname = ?, email = ? where id = ?',
    [nickname, email, id],
    (err, results) => {
      // console.log(results)
      if (results.affectedRows > 0) {
        res.send({
          status: 0,
          message: '修改用户信息成功',
        })
      } else {
        res.send({
          status: 1,
          message: '修改用户信息失败',
        })
      }
    }
  )
})

// 修改头像
router.post('/update/avatar', (req, res) => {
  const { avatar } = req.body
  const { username } = req.user
  pool.query(
    'update user set user_pic = ? where username = ?',
    [avatar, username],
    (err, results) => {
      if (results.affectedRows > 0) {
        res.send({
          status: 0,
          message: '修改用户头像成功',
        })
      } else {
        res.send({
          status: 1,
          message: '修改用户头像失败',
        })
      }
    }
  )
})

// 重置密码
router.post('/updatepwd', (req, res) => {
  let { oldPwd, newPwd } = req.body
  oldPwd = utility.md5('cy' + oldPwd + 'nx')
  newPwd = utility.md5('cy' + newPwd + 'nx')
  pool.query(
    'select * from user where username = ? and password = ?',
    [req.user.username, oldPwd],
    (err, results) => {
      if (results.length === 0) {
        return res.send({
          status: 1,
          message: '旧密码错误',
        })
      }
      // 旧密码正确时
      pool.query(
        'update user set password = ? where username = ?',
        [newPwd, req.user.username],
        (err, results) => {
          if (results.affectedRows > 0) {
            res.send({
              status: 0,
              message: '修改用户密码成功',
            })
          } else {
            res.send({
              status: 1,
              message: '修改用户密码失败',
            })
          }
        }
      )
    }
  )
})

module.exports = router
